import { constantRoutes } from '@/router'
import { getMenuList } from '@/api/system/user'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 * 判断角色是否有该菜单权限
 * 如果有code则展示菜单或者按钮
 */
function hasPermission(roles, route) {
 
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * 其中roles为数组，存储者当前用户的所有code,如 sys:user:add  ...
 * 其中routes也是数组,类型是后端的Route对象
 * 
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    //将route中的k-v键值对复制给tmp
    const tmp = { ...route }
    //判断是否有相应的权限
    if(hasPermission (roles, tmp)) {
         //获取组件
        const component = tmp.component;
        //判断该路由是否有组件
        //route.component的值为后端url
        if (route.component){ 
          //判断是否是根组件
        if (component === 'Layout'){
          tmp.component = Layout ;
        }else{
          //获取对应的具体的组件信息
          tmp.component = (resolve) => require([`@/views${component}`],resolve)
        
       }
    }
    //判断是否有子菜单
  
    if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise( (resolve,reject) => {
      //发送获取菜单请求
      getMenuList().then(response =>{
        //存放对应权限的路由信息
        let accessedRoutes;
        if(response.code === 200){
          //额外添加一个详情组件
          response.data[1].children.push({path:'/resource/weather/detail/:city',component:'/resource/weather/detail'})
          console.log(JSON.stringify(response.data[1]))
         accessedRoutes = filterAsyncRoutes(response.data , roles)
        }
      
        // 将路由信息保存到store中
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch((error)=>{
        reject(error)
      })
    
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
